from appium import webdriver
from appium.webdriver.common.appiumby import AppiumBy
from appium.webdriver.common.mobileby import MobileBy
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException, NoSuchElementException
import base64
import time

caps = {
    "platformName": "Android",
    "automationName": "uiautomator2",
    "udid": "127.0.0.1:9610",
    "appPackage": "com.zhiliaoapp.musically",
    "appActivity": "com.ss.android.ugc.aweme.main.MainActivity",
    "noReset": True,
    "autoGrantPermissions": True
}

driver = webdriver.Remote("http://127.0.0.1:4723", caps)

# 2. Push 视频文件到公共存储
local_video_path = "/fsdata/UID-NiaZXgcB6c8M/IMG_7519.mov"
remote_path = "/sdcard/Videos/IMG_7519.mov"
with open(local_video_path, "rb") as f:
    data = f.read()
b64 = base64.b64encode(data).decode('utf-8')
driver.push_file(remote_path, b64)

# 3. 强制媒体扫描更新（用 adb shell 命令或通过 driver 执行 shell）
# 这样图库／相册会识别新的视频文件
driver.execute_script("mobile: shell", {
    "command": "am",
    "args": ["broadcast", "-a", "android.intent.action.MEDIA_SCANNER_SCAN_FILE", "-d", f"file://{remote_path}"]
})

# 等待一会儿让系统更新媒体库
#time.sleep(2)

# 启动指定 Activity
driver.start_activity("com.zhiliaoapp.musically", "com.ss.android.ugc.aweme.main.MainActivity")
#//android.widget.Button[@text="Agree and continue"]

# 等待并点击 “Create” 图标
wait = WebDriverWait(driver, 10)
el = wait.until(EC.visibility_of_element_located((
    AppiumBy.XPATH,
    '//android.widget.Button[@content-desc="Create"]/android.widget.ImageView'
)))

el.click()

# 接下来处理 “Allow TikTok to take pictures …” 弹窗，如果存在就点击 While using the app
try:
    allow_while = WebDriverWait(driver, 5).until(EC.element_to_be_clickable((
        MobileBy.XPATH,
        "//android.widget.Button[@text='WHILE USING THE APP']"
    )))
    allow_while.click()
    print("权限弹窗出现，点击了 WHILE USING THE APP")
except (TimeoutException, NoSuchElementException):
    print("权限弹窗没有出现，点击访问相册图标")

try:
    allow_while = WebDriverWait(driver, 2).until(EC.element_to_be_clickable((
        MobileBy.XPATH,
        "//android.widget.Button[@text='WHILE USING THE APP']"
    )))
    allow_while.click()
    print("权限弹窗出现，点击了 WHILE USING THE APP")
except (TimeoutException, NoSuchElementException):
    print("权限弹窗没有出现，点击访问相册图标")

# 点击右下角访问相册图标（假设这个图标的定位是 content-desc="GalleryIcon"）
try:
    gallery_icon = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((
        AppiumBy.XPATH,
        "//android.widget.FrameLayout[@resource-id='com.zhiliaoapp.musically:id/blj']"
    )))
    gallery_icon.click()
    print("点击了访问相册图标")
    # 等待并处理权限提示框

except (TimeoutException, NoSuchElementException):
    print("没有找到访问相册图标，可能定位不对或者元素不在页面上")
try:
    allow_photos = WebDriverWait(driver, 2).until(EC.element_to_be_clickable((
        MobileBy.XPATH,
        "//android.widget.Button[@text='ALLOW']"
    )))
    allow_photos.click()
    print("权限提示框出现，点击了 ALLOW")
except (TimeoutException, NoSuchElementException):
    print("权限提示框没有出现，打印当前页面源代码")
#     source = driver.page_source
try:
    video_list = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((
        AppiumBy.XPATH,
        '(//android.widget.RelativeLayout[@resource-id="com.zhiliaoapp.musically:id/n30"])[2]'
    )))
    video_list.click()
    first_video = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((
        AppiumBy.XPATH,
        '//android.widget.FrameLayout[@resource-id="com.zhiliaoapp.musically:id/f4r"]'
    )))
    first_video.click()
    chose_video = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((
        AppiumBy.XPATH,
        '//android.widget.Button[@resource-id="com.zhiliaoapp.musically:id/pbw"]'
    )))
    chose_video.click()
    chose_confirm = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((
        AppiumBy.XPATH,
        '//android.widget.LinearLayout[@resource-id="com.zhiliaoapp.musically:id/k2x"]'
    )))
    chose_confirm.click()

except (TimeoutException, NoSuchElementException):
    print("没有找到视频列表，可能定位不对或者元素不在页面上")
    page_source = driver.page_source
    print(page_source)
# 打印当前页面所有元素（可选，用于调试）
# source = driver.page_source
# print(source)

driver.quit()